package com.mdd.admin.crontab;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mdd.admin.service.bill.IOrderBillPayService;
import com.mdd.admin.service.bill.OrderBillInfoService;
import com.mdd.admin.service.order.IOrderLeaseDetailsService;
import com.mdd.admin.vo.order.OrderLeaseDetailVo;
import com.mdd.common.entity.order.OrderLeaseDetails;
import com.mdd.common.enums.order.status.LeaseOrderStatusEnum;
import com.mdd.common.mapper.order.OrderLeaseDetailsMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.Schedules;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;

/**
 * 代扣日定时任务
 *
 * @Description
 * @Author 幻速
 * @Date 2023/11/12 13:56
 **/
@Slf4j
@Component("myJob")
public class WithholdJob {
    @Resource
    OrderBillInfoService orderBillInfoService;
    @Resource
    OrderLeaseDetailsMapper orderLeaseDetailsMapper;
    @Resource
    IOrderBillPayService iOrderBillPayService;

    /**
     * 每天4点执行一次，获取当月所有待结算账单
     */
    @Transactional
    public void getRepaidPlan() {
        //获取当月未激活账单，进行激活转待缴纳
        log.info("getRepaidPlan--------->执行");
        orderBillInfoService.getRepaidPlan(LeaseOrderStatusEnum.TO_BE_ACTIVATED.getCode()).forEach(orderBillInfo -> {
            try {
                orderBillInfo.setStatus(LeaseOrderStatusEnum.TO_BE_PAID.getCode());
                orderBillInfoService.updateById(orderBillInfo);
                OrderLeaseDetails orderLeaseDetails = orderLeaseDetailsMapper.selectOne(new LambdaQueryWrapper<OrderLeaseDetails>().eq(
                        OrderLeaseDetails::getOrderId, orderBillInfo.getOrderId()).last("limit 1"));
                orderLeaseDetails.setCurrentPeriod(orderBillInfo.getCurrentPeriod());
                orderLeaseDetailsMapper.updateById(orderLeaseDetails);
            }catch (Exception e){
                e.printStackTrace();
            }
        });
    }

    /**
     * 每天5点执行一次，获取当月所有待结算账单
     */
    @Transactional
    public void handle() {
        //正常还款计划，按天扣（单月租金/自然月天数）
        orderBillInfoService
                .getRepaidPlan(LeaseOrderStatusEnum.TO_BE_PAID.getCode())
                .forEach(orderBillInfo -> {
                    try {
                        iOrderBillPayService.execOrderBill(orderBillInfo);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                });
    }
}
